<template>
    <el-container style="height:100dvh;">
        <el-asdie>
            <div class="prPictureBox"></div>
        </el-asdie>
        <el-main>
            <div class="solgan">
                <span  class="solganText">一本儿<br/>有趣的口语词典</span>
                还没有账户？  
                <!-- <a class="regist" href="/regist" @click="gotoRegist">免费注册</a> -->
                <router-link  class="regist" :to="{name:'Regist'}">注册</router-link>
            </div>
            <div class="login">
                <div class="account">
                    <el-input class="account" 
                    :maxlength="11" 
                    ref="account" 
                    v-model="phoneNumVal" 
                    placeholder="输入手机号"
                    @focus="phoneFocus"
                    @blur="phoneLostFocus">帐号</el-input>
                    <span class="is-error" v-if="phoneError && phoneActive">请输入正确的手机号</span>
                
                </div>
                <div class="passwd">
                    <el-input class="passwd" 
                    ref="passwd" v-model="passWordVal" 
                    placeholder="输入密码" 
                    type="password" show-password
                    :maxlength="10"
                    @focus="passwordFocus"
                    @blur="passwordLostFocus">密码</el-input>
                    <span class="is-error" v-if="passwdError && passwdActive">密码不少于8位，包含数字和大小写字母</span> 
                </div>
                <el-checkbox v-model="free_login_7d" @change="free_login">7天内免登录</el-checkbox>
                <el-checkbox v-model="isChecked" @change="handleCheckboxChange" class="privacy"><router-link  class="documentLink" :to="{name:'UserPolicy'}">用户协议</router-link>和<router-link  class="documentLink" :to="{name:'PrivatePolicy'}">隐私政策</router-link></el-checkbox>
                <el-button v-if="isChecked" class="loginEnable" @click="login(1)">立即登录</el-button>
                <el-button v-else  class="loginDisable">立即登录</el-button>
                <router-link  class="forgetPassword" :to="{name:'ForgetPassword'}">忘记密码</router-link>
                <div class="unionLogin">联合登录 <img src="../assets/wechat.svg" @click="login(2)"/></div>
            </div>
        </el-main>
    </el-container>
    <FooterPage></FooterPage>
</template>

<script>
import { ElNotification } from 'element-plus';
import axios from 'axios';
import FooterPage from '@/components/FooterPage.vue';

export default{
    name: "LoginPage",
    data() {
        return {
            data: null,
            isChecked: false,
            free_login_7d: false,
            phoneNumVal: null,
            phoneRegex: /^1[3456789]\d{9}$/,
            passwdRegex: /^(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9]).{8,}$/,
            passWordVal: null,
            phoneActive: false,
            passwdActive: false,
            redirect_url: null,
        };
    },
    components:{
        FooterPage,
    },
    mounted() {
        //判断用户是否为已登录状态
        this.isEffect();
    },
    computed: {
        isButtonDisabled() {
            return !this.isChecked;
        },
        phoneError() {
            console.log("手机号码错误："+this.phoneRegex.test(this.phoneNumVal));
            return !this.phoneRegex.test(this.phoneNumVal);
        },
        passwdError() {
            console.log("密码错误："+this.passwdRegex.test(this.passWordVal));
            return !this.passwdRegex.test(this.passWordVal);
        }
    },
    methods: {
        handleCheckboxChange(checked) {
            this.isChecked = checked;
        },
        free_login(checked) {
            this.free_login_7d = checked;
        },
        phoneFocus() {
            this.phoneActive = true;
        },
        phoneLostFocus() {
            this.phoneActive = false;
        },
        passwordFocus() {
            this.passwdActive = true;
        },
        passwordLostFocus() {
            this.passwdActive = false;
        },
        async isEffect() {
            const login_token = this.getCookie("login_token");
            console.log("login_token: " + login_token);
            //查看该用户是否是有效免登录用户，如果是直接去词典也
            if (login_token !== null) {
                const url = await this.checkUser(login_token);
                console.log("isEffect: " + url);
                if (url !== null) {
                    this.$router.push({ path: `${url}` });
                }
                else
                    console.log('授权已过期');
            }
            else {
                console.log('请登录');
            }
            //如果不是，停留这里等着登录
        },
        //查询cookie数据
        getCookie(name) {
            const cookieString = document.cookie;
            const cookies = cookieString.split("; ");
            for (let i = 0; i < cookies.length; i++) {
                const cookie = cookies[i];
                const [cookieName, cookieValue] = cookie.split("=");
                if (cookieName === name) {
                    return cookieValue;
                }
            }
            return null;
        },
        async checkUser(login_token) {
            return new Promise((resolve, reject) => {
                const data = {
                    token: login_token,
                };
                console.log("调用7天免登录接口前检查login_token= "+data.token)
                axios.post("/api/freelogin/", data, { withCredentials: true })
                    .then(response => {
                    console.log(response.data)
                    if (response.data["code"] == 20000) {
                        console.log("checkUser: " + response.data["data"][0].url);
                        resolve(response.data["data"][0].url);
                    }
                    else {
                        resolve(null);
                    }
                })
                    .catch(error => {
                    reject(error);
                });
            });
        },
        login(loginType) {
            //type 1=帐号密码，2=微信登录
            if (loginType == 1) {
                if (this.phoneNumVal != null && this.passWordVal != null) {
                    console.log("Enter 1");
                    this.account_login();
                }
                else {
                    ElNotification({
                        message: '请填写手机号和密码信息',
                        title: '登录提醒',
                        type: "info",
                        duration: 3000,
                    });
                }
            }
            else if (loginType == 2) {
                console.log("Enter 2"),
                    this.wechat_login();
            }
        },
        //帐号登录
        async account_login() {
            //console.log("帐号密码登录");
            const data = {
                phone: this.phoneNumVal,
                password: this.passWordVal,
                free_login: this.free_login_7d,
            };
            console.log(data);
            await axios.post("/api/login/", data, { withCredentials: true })
                .then(response => {
                try {
                    if (response.data) {
                        console.log(response.data["msg"] + "&" + response.data["code"]);
                        ElNotification({
                            message: response.data["msg"],
                            title: response.data["code"],
                            type: "info",
                            duration: 3000,
                        });
                        //如果后端验证成功，执行页面跳转
                        if (response.data["code"] == 20000) {
                            console.log("url: " + (response.data["data"][0].url));
                            //const redirect_url = response.data["data"][0].url;
                            this.redirect_url = response.data["data"][0].url;
                            console.log("url: " + this.redirect_url);
                            const cookies = document.cookie;
                            console.log("cookies ~ " + cookies);
                            //this.$router.push({path:`${redirect_url}${data['phone']}`});
                            this.$router.push({ path: `${this.redirect_url}` });
                        }
                    }
                }
                catch (error) {
                    console.log(error);
                }
            });
        },
        //微信登录
        async wechat_login() {
            if (!this.isChecked) {
                ElNotification({
                    message: "请先同意用户政策和隐私协议",
                    title: "系统消息",
                    type: "info",
                    duration: 3000,
                });
            }
            else {
                console.log("wechat login");
            }
        },
    },
    components: { FooterPage }
}
</script>

<style scoped>
.forgetPassword{
 text-decoration: none;
 display: block;
 margin:2dvh 0 2dvh 8dvw;  
}
.documentLink{
    text-decoration: none;
}

div.account{
    margin-bottom: 2dvh;
}
div.passwd{
    margin-bottom: 2dvh;
}
.is-error{
   font-size: small;
   font-weight: 300;
   color:red;
   display: block;
   margin: 0;
}
button.el-button.loginEnable{
    margin-top: 7dvh;
    display: block;
    width: 22.5dvw;
    font-weight: 600;
    background-color:#2a55e2 ;
    color: #fff;
}

button.el-button.loginDisable{
    margin-top: 7dvh;
    display: block;
    width: 22.5dvw;
    font-weight: 600;
    background-color:#f4f4f5 ;
    color: #909399;
}
button.el-button.findPasswd{
    display: block;
    margin: 1dvh 9dvw;
    font-weight: 600;
    color: #316adb;
}
div.prPictureBox{
    background-image:url('https://sam-test.oss-cn-beijing.aliyuncs.com/assets/loginbkimg%40170%20(1).png') ;
    background-repeat: no-repeat;
    background-size: cover;
    width: 67.5dvw;
    height: 100dvh;
}

div.solgan{
    height: 25dvh;
    margin-top:8.2dvh;
    padding-left: 3dvw;
    text-align: left;
    font-size: 15px;
    color: rgba(0,0,0,0.65);
    font-weight: 500;
}

div.login{
    margin:8.2dvh auto;
    padding-left: 3dvw;
    padding-right: 3dvw;
    text-align: left;
    font-size: 15px;
    color: rgba(0,0,0,0.65);
    font-weight: 500;
}

span.solganText{
    display: block;
    padding-bottom: 2dvh;
    color: #2245ba;
    font-size: 22pt;
    font-weight: bolder;
}

.regist{
    color:#316adb;
    font-size: 14px;
    text-decoration: none;
}
</style>